import { isEmptyStr } from 'jdf-util';
import {
  differenceBy,
  groupBy,
  orderBy
} from 'lodash-es';

/**
 * 设置选择的主抄送部门顺序返回
 * @param {*} val
 */
const setDeptOrder = (val, sendData) => {
  // 将领导列表移除
  const orgList = val.filter(t => t.type === 'ORG');
  const leaderList = differenceBy(val, orgList, 'id');
  const orderVal = orderBy(orgList, ['order', 'parentOrder'], ['asc', 'asc']);
  const datas = groupBy(orderVal, 'parentName');
  const orderSendData = orderBy(sendData, ['order'], ['asc']);
  const res = orderSendData.map((t) => datas[t.orgName]?.map((v, index) => `${index === 0
    ? v.aliasPrefix ?? '' : ''}${v.orgName}`).join('、') ?? '');
  const leaderArr = orderBy(leaderList, 'order').map(t => t.name).join('、');
  return [...[leaderArr], ...res].filter(t => !isEmptyStr(t));
};

export default setDeptOrder;
